/**
 * Created by Adi(adi@imeth.cn) on 2018/8/29.
 */
import React, { Component } from 'react';
import { Select } from 'antd';
import PropTypes from 'prop-types';
import { autobind } from 'core-decorators';

const Option = Select.Option;

/**
 * 下拉选择
 */

@autobind
class Selector extends Component {
  static propTypes = {
    allowClear: PropTypes.bool,
    selectList: PropTypes.array.isRequired, // 下拉显示列表 应有 value label
    defaultValue: PropTypes.string, // 默认展示项
    mode: PropTypes.string, // 模式  multiple tags
    onSearch: PropTypes.func, // 文本变化调用
    onChange: PropTypes.func, // 选中调用 （包括value值改变）
    placeholder: PropTypes.string, // 默认文本
    maxTagCount: PropTypes.number, // 最多显示多少tag
    width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), // 选择框宽度
    disabled: PropTypes.bool,
    showSearch: PropTypes.bool,
  };

  static defaultProps = {
    maxTagCount: 10,
    placeholder: '请选择',
    width: '217px',
    allowClear: true,
    disabled: false,
    showSearch: true,
  };

  constructor(props) {
    super(props);
    let { selectList, listResult, disabled } = this.props;
    this.state = {
      selectList,
      listResult,
      list: [],
      disabled,
    };
  }

  // react16.3新生命周期 接收props 修改state 返回类似setState()
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.selectList !== prevState.selectList) {
      const list = [];
      for (let i = 0; i < nextProps.selectList.length; i++) {
        list.push(<Option key={nextProps.selectList[i].value}>{nextProps.selectList[i].label}</Option>);
      }
      return {
        selectList: nextProps.selectList,
        list,
      };
    }

    if (nextProps.disabled !== prevState.disabled) {
      return {
        disabled: nextProps.disabled,
      };
    }
    // 返回Null 不修改state
    return null;
  }

  componentDidMount() {
    const { selectList } = this.state;
    const list = [];
    for (let i = 0; i < selectList.length; i++) {
      list.push(<Option key={selectList[i].value}>{selectList[i].label}</Option>);
    }
    this.setState({ list });
  }

  render() {
    const { list, disabled } = this.state;
    const { defaultValue, mode, placeholder, maxTagCount, width, allowClear, showSearch } = this.props;
    return (
      <Select
        placeholder={placeholder}
        maxTagCount={maxTagCount}
        mode={mode}
        defaultValue={defaultValue}
        onSearch={this._onSearch}
        onChange={this._onChange}
        style={{ width: width }}
        allowClear={allowClear}
        disabled={disabled}
        showSearch={showSearch}
      >
        {list}
      </Select>
    );
  }

  _onSearch(value) {
    const { onSearch } = this.props;
    onSearch && onSearch(value);
  }

  _onChange(value) {
    const { onChange } = this.props;
    onChange && onChange(value);
  }
}

export default Selector;
